package org.wangblue.query;

import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermsQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.wangblue.common.Client;

import java.util.Map;


/**
 * @Description: 高亮查询
 * @Author: WangBlue
 * @Create: 2024-10-24 14:06
 * @Version: 1.0
 **/

public class HeightLightQuery {
    private static final String INDEX_NAME = "user";
    public static void main(String[] args) {
        try (RestHighLevelClient client = Client.getClient()) {
            // 1. 指定索引
            SearchRequest request = new SearchRequest().indices(INDEX_NAME);

            // 2. 构建 查询请求体构造器
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

            // 3. 构建查询方式： 高亮查询
            TermsQueryBuilder termsQueryBuilder = QueryBuilders.termsQuery("sex", "男");

            // 4. 设置查询方式
            sourceBuilder.query(termsQueryBuilder);

            // 5. 设置高亮字段
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.preTags("<font color='red'>");//设置标签前缀
            highlightBuilder.postTags("</font>");//设置标签后缀
            highlightBuilder.field("sex");//设置高亮字段

            // 6. 设置高亮构建对象
            sourceBuilder.highlighter(highlightBuilder);

            // 7. 设置请求体
            request.source(sourceBuilder);

            // 8. 客户端发送请求， 获取响应对象
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);

            //9. 打印响应结果
            SearchHits hits = response.getHits();
            System.out.println("took::"+response.getTook());
            System.out.println("time_out::"+response.isTimedOut());
            System.out.println("total::"+hits.getTotalHits());
            System.out.println("max_score::"+hits.getMaxScore());
            System.out.println("hits::::>>");
            for (SearchHit hit : hits) {
                String sourceAsString = hit.getSourceAsString();
                System.out.println(sourceAsString);
                //打印高亮结果
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                System.out.println(" 打印高亮结果 " + highlightFields);
            }
            System.out.println("<<::::");


        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}
